const express = require("express");
const router = express.Router();
const dayjs = require("dayjs");
const utc = require("dayjs/plugin/utc");
const timezone = require("dayjs/plugin/timezone");

dayjs.extend(utc);
dayjs.extend(timezone);
let connectDAO = require("./connect.js");

// 获取当前用户的所有邀请用户
router.get("/current_all_invited_user", function (req, res) {
  const { inviter_user_id } = req.query;
  connectDAO.queryDataBySQL(
    `SELECT * FROM invitations WHERE inviter_user_id = '${inviter_user_id}'`,
    (result) => {
      res.send({ code: 200, msg: "success" ,result});
    }
  ).catch((err) => {
    res.send({ code: 400, msg: "400",err });
  });;
});

// 绑定用户
router.post("/binding_new_user", function (req, res) {
  const {
    invite_code,
    inviter_user_id,
    invited_user_id,
    inviterd_user_name = "",
    isEffective,
  } = req.body;
  const time = dayjs().tz("America/New_York").valueOf();
  connectDAO
    .queryDataBySQL(
      `INSERT INTO invitations VALUES (DEFAULT, '${inviter_user_id}', '${invited_user_id}','${invite_code}',FROM_UNIXTIME(${time}/1000),'${isEffective}','${inviterd_user_name}',0)`
    )
    .then(() => {
      res.send({ code: 200, msg: "binding" });
    })
    .catch((err) => {
      res.send({ code: 400, msg: "400",err });
    });
});

// 领取邀请的用户奖励
router.put("/received_new_user",function(req,res){
    const {
        inviter_user_id,
        invited_user_ids,
      } = req.body;
      connectDAO
      .queryDataBySQL(
        `UPDATE invitations SET received = 1 WHERE inviter_user_id = ${inviter_user_id} AND invited_user_id IN (${invited_user_ids.join()});`
      )
      .then(() => {
        res.send({ code: 200, msg: "received" });
      })
      .catch((err) => {
        res.send({ code: 400, msg: "400",err });
      });
})

module.exports = router;
